<script setup lang="ts">
import { reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import {
  UserOutlined,
  LockOutlined,
  WechatOutlined,
  WeiboOutlined,
  MobileOutlined,
  SafetyOutlined
} from '@ant-design/icons-vue';
import { login } from "../api/auth/";
import { useAuthStore } from "../store/auth";

interface FormState {
  username: string;
  password: string;
  remember: boolean;
}

interface PhoneFormState {
  phone: string;
  code: string;
}

const props = defineProps<{
  visible: boolean;
}>();

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void;
  (e: 'login-success'): void;
}>();

const activeKey = ref('account');
const loading = ref(false);
const countdown = ref(0);

const formState = reactive<FormState>({
  username: '',
  password: '',
  remember: true
});

const phoneFormState = reactive<PhoneFormState>({
  phone: '',
  code: ''
});

const handleCancel = () => {
  emit('update:visible', false);
};

const onFinish = async (values: FormState) => {
  loading.value = true;
  try {
    const response = await login({
      username: values.username,
      password: values.password
    });
    if (response.code === 0) {
      const authStore = useAuthStore();
      // 设置token和过期时间，这里假设过期时间为24小时后
      const expiresAt = Date.now() + 24 * 60 * 60 * 1000;
      authStore.setToken(response.data.access_token, expiresAt);
      message.success('登录成功');
      emit('login-success');
      emit('update:visible', false);
    } else {
      message.error(response.msg || '登录失败');
    }
  } catch (error) {
    console.error('登录请求失败:', error);
    message.error('网络请求失败，请检查网络连接后重试');
  } finally {
    loading.value = false;
  }
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

const onPhoneFinish = async (values: PhoneFormState) => {
  loading.value = true;
  try {
    // 这里添加实际的手机号登录逻辑
    console.log('Phone login success:', values);
    message.success('登录成功');
    emit('login-success');
    handleCancel();
  } catch (error) {
    message.error('登录失败，请重试');
  } finally {
    loading.value = false;
  }
};

const sendCode = async () => {
  if (!phoneFormState.phone) {
    message.error('请输入手机号');
    return;
  }
  // 这里添加发送验证码的逻辑
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};</script>

<template>
  <a-modal
    :open="visible"
    @update:open="(val) => $emit('update:visible', val)"
    :footer="null"
    :closable="true"
    :maskClosable="true"
    width="380px"
    class="login-modal"
    @cancel="handleCancel"
  >
    <div class="login-box">
      <div class="login-header">
        <h2 class="logo">Becho</h2>
        <p class="subtitle">欢迎回来</p>
      </div>

      <!-- 登录方式切换 -->
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="account" tab="账号密码登录">
          <a-form
            :model="formState"
            name="login"
            class="login-form"
            @finish="onFinish"
            @finishFailed="onFinishFailed"
          >
            <a-form-item
              name="username"
              :rules="[{ required: true, message: '请输入用户名' }]"
            >
              <a-input
                v-model:value="formState.username"
                placeholder="用户名"
                size="large"
              >
                <template #prefix>
                  <user-outlined />
                </template>
              </a-input>
            </a-form-item>

            <a-form-item
              name="password"
              :rules="[{ required: true, message: '请输入密码' }]"
            >
              <a-input-password
                v-model:value="formState.password"
                placeholder="密码"
                size="large"
              >
                <template #prefix>
                  <lock-outlined />
                </template>
              </a-input-password>
            </a-form-item>

            <div class="form-footer">
              <a-checkbox v-model:checked="formState.remember">记住我</a-checkbox>
              <a class="forgot-link">忘记密码？</a>
            </div>

            <a-form-item>
              <a-button
                type="primary"
                html-type="submit"
                class="login-button"
                size="large"
                :loading="loading"
              >
                登录
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <a-tab-pane key="phone" tab="手机号登录">
          <a-form
            :model="phoneFormState"
            name="phoneLogin"
            class="login-form"
            @finish="onPhoneFinish"
          >
            <a-form-item
              name="phone"
              :rules="[{ required: true, message: '请输入手机号' }]"
            >
              <a-input
                v-model:value="phoneFormState.phone"
                placeholder="手机号"
                size="large"
                addonBefore="+86"
              >
                <template #prefix>
                  <mobile-outlined />
                </template>
              </a-input>
            </a-form-item>

            <a-form-item
              name="code"
              :rules="[{ required: true, message: '请输入验证码' }]"
            >
              <a-row :gutter="8">
                <a-col :span="16">
                  <a-input
                    v-model:value="phoneFormState.code"
                    placeholder="验证码"
                    size="large"
                  >
                    <template #prefix>
                      <safety-outlined />
                    </template>
                  </a-input>
                </a-col>
                <a-col :span="8">
                  <a-button
                    size="large"
                    :disabled="!!countdown"
                    @click="sendCode"
                    block
                  >
                    {{ countdown ? `${countdown}s` : '获取验证码' }}
                  </a-button>
                </a-col>
              </a-row>
            </a-form-item>

            <a-form-item>
              <a-button
                type="primary"
                html-type="submit"
                class="login-button"
                size="large"
                :loading="loading"
              >
                登录
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <a-tab-pane key="qrcode" tab="扫码登录">
          <div class="qrcode-container">
            <div class="qrcode-box">
              <img src="/qr-placeholder.png" alt="扫码登录" class="qrcode-image" />
            </div>
            <p class="qrcode-tip">暂不支持扫码登录</p>
          </div>
        </a-tab-pane>
      </a-tabs>

      <div class="divider">
        <span>其他登录方式</span>
      </div>

      <div class="social-login">
        <a-button class="social-button wechat">
          <template #icon><wechat-outlined /></template>
          微信登录
        </a-button>
        <a-button class="social-button weibo">
          <template #icon><weibo-outlined /></template>
          微博登录
        </a-button>
      </div>

      <div class="agreement-tip">
        登录即表示同意
        <a href="#" class="link">《用户协议》</a>
        <a href="#" class="link">《隐私政策》</a>
        <a href="#" class="link">《儿童/青少年个人信息保护规则》</a>
      </div>
    </div>
  </a-modal>
</template>



<style scoped>
.login-modal :deep(.ant-modal-content) {
  border-radius: 16px;
  overflow: hidden;
}

.login-box {
  padding: 20px 0;
}

.login-header {
  text-align: center;
  margin-bottom: 24px;
}

.logo {
  font-size: 28px;
  font-weight: bold;
  color: #6893AC;
  margin: 0;
}

.subtitle {
  color: #8c8c8c;
  margin-top: 8px;
}

.login-form {
  width: 100%;
}

.form-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.forgot-link {
  color: #6893AC;
  cursor: pointer;
}

.forgot-link:hover {
  color: #95C7E0;
}

.login-button {
  width: 100%;
  background: #6893AC;
  border-color: #6893AC;
}

.login-button:hover {
  background: #95C7E0;
  border-color: #95C7E0;
}

.divider {
  position: relative;
  text-align: center;
  margin: 24px 0;
  color: #8c8c8c;
}

/* 添加验证码按钮样式 */
.ant-form-item .ant-col-8 .ant-btn {
  font-size: 13px;
  padding: 0 8px;
  height: 40px;
  white-space: nowrap;
}

.divider::before,
.divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 30%;
  height: 1px;
  background: #f0f0f0;
}

.divider::before {
  left: 0;
}

.divider::after {
  right: 0;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 24px;
}

.social-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 24px;
}

.wechat {
  color: #07C160;
  border-color: #07C160;
}

.weibo {
  color: #E6162D;
  border-color: #E6162D;
}

.qrcode-container {
  text-align: center;
  padding: 24px 0;
}

.qrcode-box {
  width: 180px;
  height: 180px;
  margin: 0 auto 16px;
  padding: 8px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.qrcode-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.qrcode-tip {
  color: #8c8c8c;
  margin: 0;
}

.agreement-tip {
  font-size: 12px;
  color: #8c8c8c;
  text-align: center;
  line-height: 1.5;
}

.link {
  color: #6893AC;
  text-decoration: none;
}

.link:hover {
  color: #95C7E0;
}
</style>